import { LoadingOutlined, PlusOutlined } from '@ant-design/icons';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import type { FormInstance } from 'antd';
import { Button, Drawer, Form, Input, message, Modal, Popconfirm, Upload } from 'antd';
import type { RcFile, UploadChangeParam, UploadFile, UploadProps } from 'antd/lib/upload/interface';
import React, { useRef, useState } from 'react';
import AppListDetail from './components/ApplistDetail';
import UpdateAppItem from './components/UpdateAppItem';
import type { AppListItem } from './data';
import { addAppLinks, deleteLinksItemByid, getList } from './service';
const AppList: React.FC<{}> = () => {
  const [isShowDetail, setIsShowDetail] = useState(false);
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [isModalVisibleU, setIsModalVisibleU] = useState(false);
  const [ownid, setOwnid] = useState('');
  const [imageUrl, setImageUrl] = useState<string>();
  const [loading, setLoading] = useState(false);
  const actionRef = useRef<ActionType>();
  const [apprecommand, setApprecommand] = useState({} as AppListItem);
  const beforeUpload = (file: RcFile) => {
    const isLt1M = file.size / 1024 / 1024 < 1;
    if (!isLt1M) {
      message.error('图片必须小于1M!');
    }
    return isLt1M;
  };
  const formRef = React.createRef<FormInstance>();
  const onPreview = async (file: UploadFile) => {
    let src = file.url as string;
    if (!src) {
      src = await new Promise((resolve) => {
        const reader = new FileReader();
        reader.readAsDataURL(file.originFileObj as RcFile);
        reader.onload = () => resolve(reader.result as string);
      });
    }
    const image = new Image();
    image.src = src;
    const imgWindow = window.open(src);
    imgWindow?.document.write(image.outerHTML);
  };
  const handleChange: UploadProps['onChange'] = (info: UploadChangeParam<UploadFile>) => {
    if (info.file.status === 'uploading') {
      setLoading(true);
      return;
    }
    if (info.file.status === 'done') {
      setImageUrl(info.file.response.data.url);
    }
  };
  const uploadButton = (
    <div>
      {loading ? <LoadingOutlined /> : <PlusOutlined />}
      <div style={{ marginTop: 8 }}>点击上传图片</div>
      <div style={{ marginTop: 8 }}>(144*144)</div>
    </div>
  );
  const changeShowUpdate = () => {
    setIsModalVisibleU(false);
    actionRef.current?.reload();
  };
  const deleteByid = (id: string) => {
    deleteLinksItemByid(id)
      .then((res) => {
        if (res?.success) {
          message.success('删除成功');
          actionRef.current?.reload();
        } else {
          message.success('删除失败');
        }
      })
      .catch((err) => {
        message.error(err);
      });
    actionRef.current?.reload();
  };
  const onFinish = (values: any) => {
    const data = { ...values, ...{ icon: imageUrl } };
    addAppLinks(data)
      .then((res) => {
        if (res?.success == true) {
          message.success('添加成功');
          formRef.current!.resetFields();
          setIsModalVisible(false);
          actionRef.current?.reload();
        } else {
          message.error('添加失败');
        }
      })
      .catch((err) => {
        message.error(err);
      });
  };

  const columns: ProColumns<AppListItem>[] = [
    {
      title: 'id',
      dataIndex: 'id',
      hideInTable: true,
      hideInSearch: true,
    },
    {
      title: '小程序appid',
      dataIndex: 'appId',
      hideInTable: true,
      hideInSearch: true,
    },
    {
      title: '小程序名称',
      dataIndex: 'name',
    },
    {
      title: '小程序图标',
      dataIndex: 'icon',
      hideInSearch: true,
      valueType: 'image',
    },
    {
      title: '小程序链接',
      dataIndex: 'links',
      hideInSearch: true,
    },
    {
      title: '操作',
      key: 'option',
      width: 300,
      valueType: 'option',
      render: (text, record) => [
        <a
          key="editable"
          onClick={() => {
            setIsModalVisibleU(true);
            setOwnid(record.id);
          }}
        >
          修改
        </a>,

        <a
          key="detail"
          onClick={() => {
            setApprecommand(record);
            setIsShowDetail(true);
          }}
        >
          详情
        </a>,
        <Popconfirm
          key={record.id}
          title="你确定要删除此项吗?"
          okText="是"
          cancelText="否"
          onConfirm={() => {
            deleteByid(record.id);
          }}
        >
          <a href="">删除</a>
        </Popconfirm>,
      ],
    },
  ];

  return (
    <>
      <PageHeaderWrapper>
        <ProTable<AppListItem>
          actionRef={actionRef}
          columns={columns}
          search={{
            labelWidth: 'auto',
            span: { xs: 24, sm: 12, md: 8, lg: 8, xl: 8, xxl: 6 },
          }}
          pagination={{ defaultPageSize: 6, size: 'default' }}
          rowKey={'id'}
          headerTitle="小程序列表"
          toolBarRender={() => [
            <Button
              key="button"
              icon={<PlusOutlined />}
              type="primary"
              onClick={() => {
                setIsModalVisible(true);
              }}
            >
              添加
            </Button>,
          ]}
          request={(params) => getList(params)}
        />
        <Drawer
          visible={isShowDetail}
          size="default"
          title="小程序详情"
          onClose={() => {
            setIsShowDetail(false);
          }}
        >
          {isShowDetail && (
            // <ProDescriptions<ReservationOrder>
            //   // eslint-disable-next-line @typescript-eslint/no-unused-expressions
            //   request={async ()=>({data:Order})}
            //   columns={columns.filter((i)=>i.valueType != 'option')}
            //   column={1}

            //  />
            <AppListDetail id={apprecommand.id} />
          )}
          {/* <ReservationOrderDetail /> */}
        </Drawer>
        <Modal
          title="更新小程序"
          footer={null}
          visible={isModalVisibleU}
          bodyStyle={{ paddingLeft: 272, paddingRight: 272 }}
          onCancel={() => {
            setIsModalVisibleU(false);
          }}
          width={1184}
        >
          {<UpdateAppItem id={ownid} changeIsShowUpdate={changeShowUpdate} />}
        </Modal>
        <Modal
          title="添加小程序"
          footer={null}
          visible={isModalVisible}
          bodyStyle={{ paddingLeft: 272, paddingRight: 272 }}
          onCancel={() => {
            setIsModalVisible(false);
          }}
          width={1184}
        >
          <Form
            name="basic"
            onFinish={onFinish}
            colon={false}
            labelWrap={true}
            layout="vertical"
            // labelCol={{ span: 8 }}
            // wrapperCol={{ span: 16 }}
            initialValues={{ remember: true }}
            autoComplete="off"
            ref={formRef}
          >
            <Form.Item
              label="小程序名称"
              name="name"
              // labelAlign={{left}}}
              // wrapperCol={{span: 6, offset: 2}}
              // labelCol={span: 3, offset: 12}
              rules={[{ required: true, message: '请输入小程序名称' }]}
            >
              <Input placeholder="请输入" />
            </Form.Item>
            <Form.Item
              label="AppID"
              name="appId"
              // labelAlign={{left}}}
              // wrapperCol={{span: 6, offset: 2}}
              // labelCol={span: 3, offset: 12}
              rules={[{ required: true, message: '请输入appid' }]}
            >
              <Input placeholder="请输入" />
            </Form.Item>
            <Form.Item
              label="小程序链接"
              name="links"
              // labelAlign={{left}}}
              // wrapperCol={{span: 6, offset: 2}}
              // labelCol={span: 3, offset: 12}
              rules={[{ required: true, message: '请输入小程序链接' }]}
            >
              <Input placeholder="请输入" />
            </Form.Item>
            <Form.Item
              label="上传图标"
              name="icon"
              // labelAlign={{left}}}
              // wrapperCol={{span: 6, offset: 2}}
              // labelCol={span: 3, offset: 12}
              rules={[{ required: true, message: '请上传图标图片' }]}
            >
              <Upload
                name="file"
                listType="picture-card"
                className="avatar-uploader"
                showUploadList={false}
                onPreview={onPreview}
                onChange={handleChange}
                beforeUpload={beforeUpload}
                action="/api/file/upload/singleImage"
                maxCount={1}
              >
                {imageUrl ? (
                  <img src={imageUrl} alt="avatar" style={{ width: '100%' }} />
                ) : (
                  uploadButton
                )}
              </Upload>
            </Form.Item>
            <Form.Item>
              <Button type="primary" htmlType="submit">
                提交
              </Button>
            </Form.Item>
          </Form>
        </Modal>
      </PageHeaderWrapper>
    </>
  );
};
export default AppList;
